package Server.controller;

import Plug.operLog.OperLog;
import Plug.result.RetResponse;
import Plug.result.RetResult;
import Server.dao.UserSiteDao;
import Server.dao.UsersDao;
import Server.entity.ShopCar;
import Server.entity.UserSite;
import Server.entity.Users;
import Server.tool.BeanToJson;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("SiteController")
public class SiteController {
    @Autowired
    private UserSiteDao userSiteDao;
    @Autowired
    private UsersDao usersDao;
    @RequestMapping("List")
    public RetResult List(@RequestBody JSONObject jsonObject){
        UserSite entity = (UserSite) BeanToJson.jsonTobean(jsonObject.getJSONObject("common").toString(), UserSite.class);
        int page = Integer.parseInt(jsonObject.getString("page")) - 1;
        int size = Integer.parseInt(jsonObject.getString("limit"));
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "uuid");
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("users.name", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<UserSite> example = Example.of(entity, matcher);
        Page<UserSite> userlist = userSiteDao.findAll(example, pageable);
        return RetResponse.makeRsp(0, "成功", userlist.getContent(), (int) userlist.getTotalElements());
    }
    @OperLog("添加修改收货地址")
    @RequestMapping("Save")
    public RetResult Save(@RequestBody UserSite userSite){
        Users fspuser = (Users) SecurityUtils.getSubject().getSession().getAttribute("Users");
        fspuser=usersDao.findByUuid(fspuser.getUuid());
        userSite.setUsers(fspuser);
        if(userSite.getIsBank()==1){
            List<UserSite> ls = userSiteDao.findByUsers(fspuser);
            for(UserSite lk:ls){
                lk.setIsBank(0);
                userSiteDao.save(lk);
            }
        }
        userSiteDao.save(userSite);
        return RetResponse.makeOKRsp();
    }
    /*
    *
    * 获得用户所有收货地址
    *
    * */
    @RequestMapping("GetUserSite")
    public RetResult GetUserSite(){
        Users fspuser = (Users) SecurityUtils.getSubject().getSession().getAttribute("Users");
        fspuser=usersDao.findByUuid(fspuser.getUuid());
        return RetResponse.makeOKRsp(userSiteDao.findByUsers(fspuser));
    }
}
